package com.example.forum.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.forum.MyQuery;
import com.example.forum.commons.tools.Transfer.DataTransfer;
import com.example.forum.entity.*;
import com.example.forum.mapper.*;
import com.example.forum.service.ITThemeService;
import com.example.forum.vo.PageDto;
import com.example.forum.vo.ThemeDto;
import com.example.forum.vo.ThemeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author why
 * @since 2020-04-22
 */
@Service
public class TThemeServiceImpl extends ServiceImpl<TThemeMapper, TTheme> implements ITThemeService {

    @Autowired
    TThemeMapper tThemeMapper;

    @Autowired
    DataTransfer dataTransfer;

    @Autowired
    TClickzanServiceImpl tClickzanService;

    @Autowired
    TBlockMapper blockMapper;

    @Autowired
    TAuditpolicyMapper auditpolicyMapper;

    @Autowired
    TBlockareaMapper blockareaMapper;

    @Autowired
    TSensitivewordsMapper sensitivewordsMapper;

    @Autowired
    TThemecontentMapper tThemecontentMapper;

    @Autowired
    TThemepictureMapper tThemepictureMapper;


    @Override
    public PageDto getThemeReplyInfo(Map<Object, Object> map) {
        Integer type = Convert.toInt(map.get("type"));
        if (type == -1) {//查询所有
            return new PageDto(tThemeMapper.queryThemsAndReplyCount(map), tThemeMapper.queryThemsAndReply(map));
        } else {
            return new PageDto(tThemeMapper.queryThemOrReplyCount(map), tThemeMapper.queryThemOrReply(map));
        }
    }

    @Override
    public PageDto queryMyThemeOrReply(HashMap<Object, Object> map) {
        return new PageDto(tThemeMapper.queryMyThemeOrReplyCount(map), tThemeMapper.queryMyThemeOrReply(map));
    }

    @Override
    public PageDto homeThemeRecommend(TAppuser appuser, Integer page, Integer pageSize) {
        HashMap<Object, Object> parms = new HashMap<>();
        parms.put("streetid", appuser.getStreetid());
        parms.put("regionid", appuser.getRegionid());
        parms.put("neighborhoodcommitteeid", appuser.getNeighborhoodcommitteeid());
        parms.put("userId", appuser.getId());
        parms.put("page", page);
        parms.put("pageSize", pageSize);
        List<ThemeDto> themeDtoList = tThemeMapper.homeThemeRecommend(parms);
        Long count = tThemeMapper.homeThemeRecommendCount(parms);
        return new PageDto(count, themeDtoList);
    }

    @Transactional
    @Override
    public boolean CreateTheme(ThemeModel themeModel, String userId) {
        var theme = new TTheme();
        theme = (TTheme) dataTransfer.getObjectFromObject(theme, themeModel);
        theme.setCreatoruserid(userId);

        TBlockarea blockarea = blockareaMapper.selectById(theme.getBlockareaid());
        TBlock block = blockMapper.selectById(blockarea.getBlockid());
        //查询板块的审核规则
        TAuditpolicy auditpolicy = auditpolicyMapper.selectById(block.getPolicyid());
        if (auditpolicy.getPolicyname().equals("敏感词过滤后展现")) {
            //查询敏感词
            List<String> terms = sensitivewordsMapper.selectList(new MyQuery<TSensitivewords>().select("terms").eq("isrelease", 1))
                    .stream().map(TSensitivewords::getTerms).collect(Collectors.toList());
            //内容过滤
            for (String term : terms) {
                if (theme.getContent().contains(term)) {
                    StringBuilder str = new StringBuilder();
                    for (char c : term.toCharArray()) {
                        str.append("*");
                    }
                    theme.setContent(theme.getContent().replaceAll(term, str.toString()));
                }
            }
            theme.setStatus(2);//审核通过

        } else if (auditpolicy.getPolicyname().equals("人工审核后展现")) {
            theme.setStatus(2);//默认审核通过
        }

        //保存文章
        theme.setCreatoruserid(userId);
        theme.setIsrecommend(false);
        theme.setDeletetype(0);
        tThemeMapper.insert(theme);

        //保存内容
        TThemecontent themecontent = new TThemecontent();
        themecontent.setThemeid(theme.getId());
        themecontent.setContent(theme.getContent());
        themecontent.setIsvisible(true);
        tThemecontentMapper.insert(themecontent);
        //保存图片
        for (String imgUrl : themeModel.getImgUrls()) {
            TThemepicture tThemepicture = new TThemepicture();
            tThemepicture.setThemeid(theme.getId());
            String[] split = imgUrl.split("/");
            tThemepicture.setFilenames(split[split.length - 1]);
            tThemepicture.setFileurls(imgUrl);
            tThemepicture.setIsvisible(true);
            tThemepictureMapper.insert(tThemepicture);
        }
        return true;
    }

    //获取当前位置所有主提
    @Override
    public PageDto getThemesByAreaId(Integer pageIndex, Integer pageSize, String blockId, String areaId, String currentUserId) {

        HashMap<Object, Object> parms = new HashMap<>();
        parms.put("pageIndex",pageIndex);
        parms.put("pageSize",pageSize);
        parms.put("blockId",blockId);
        parms.put("areaId",areaId);

        //分页获取当前位置所有主题
//        List<TThemesByAreaIdModel> tThemesList = tThemeMapper.getThemesByAreaId(parms);
        List<TThemesByAreaIdModel> tThemesList = tThemeMapper.getThemesByAreaId(pageIndex, pageSize, blockId, areaId);
        //获取当前位置所有主题数目
        Long count = tThemeMapper.getThemesByAreaIdCount(blockId, areaId);
        //isIsClickZan  判断当前用户是否点赞了这个主题
        //themeID 当前用户ID
        tThemesList.forEach(tThemesByAreaIdModel -> {

            Boolean clickZan = tClickzanService.isClickZan(tThemesByAreaIdModel.getId(), currentUserId);
            tThemesByAreaIdModel.setIsClickZan(clickZan);
        });


        return new PageDto(count, tThemesList);
    }

    @Override
    public TTheme getThemesDetail(String themeId,String userId) {
        HashMap map = new HashMap<>();
        map.put("themeId",themeId);
        map.put("userId",userId);
        return tThemeMapper.getThemesDetail(map);
    }

}
